Page({
  data: {
    cartData: [],
    totalPrice: 0,
    checked: false
  },

  onLoad: function () {
    this.checkRefreshCart();
  },

  onShow: function () {
    this.checkRefreshCart();
  },

  checkRefreshCart: function () {
    const app = getApp();
    if (app && app.globalData && app.globalData.eventBus && app.globalData.eventBus.refreshCart) {
      app.globalData.eventBus.refreshCart = false;
      setTimeout(() => {
        this.refreshCart();
      }, 300);
    } else if (this.data.cartData.length === 0) {
      this.getCartList();
    }
    this.calculateTotalPrice();
  },

  getCartList: function () {
    const token = wx.getStorageSync('token'); 
    const userid = wx.getStorageSync('userid'); 

    if (!token) {
      wx.showToast({
        title: '登录已失效，请重新进入小程序',
        icon: 'none'
      });
      this.login();
      return;
    }

    wx.request({
      url: 'http://47.94.6.186:3001/api/cart/list', 
      method: 'POST',
      header: {
        'token': token 
      },
      data: {
        userid: userid 
      },
      success: (res) => {
        this.setData({
          cartData: res.data.data 
        });
      },
      fail: (err) => {
        // 检查是否是token无效的错误
        if (err.errMsg && err.errMsg.includes('token')) {
          wx.showToast({
            title: '登录已失效，请重新登录',
            icon: 'none'
          });
          this.login();
        }
      }
    });
  },

  // 刷新购物车数据
  refreshCart: function() {
    this.getCartList();
  },

  // 计算总价
  calculateTotalPrice: function() {
    let totalPrice = 0;
    this.data.cartData.forEach(item => {
      if (item.flag) {
        totalPrice += item.num * item.originprice;
      }
    });
    this.setData({
      totalPrice: totalPrice
    });
  },



  // 删除购物车单条数据
  cartDeleteHandler: function(e) {
    const cartid = e.currentTarget.dataset.cartid;
    const token = wx.getStorageSync('token');

    if (!token) {
      wx.showToast({
        title: '登录已失效，请重新登录',
        icon: 'none'
      });
      this.login();
      return;
    }

    wx.request({
      url: 'http://47.94.6.186:3001/api/cart/remove',
      method: 'POST',
      header: {
        'token': token
      },
      data: {
        cartid: cartid
      },
      success: (res) => {
        if (res.data.code === '200' || res.data.code === 200) {
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
          this.refreshCart();
        } else {
          wx.showToast({
            title: '删除失败: ' + res.data.msg || '未知错误',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络异常，删除失败',
          icon: 'none'
        });
      },
      complete: () => {}
    });
  },

  login: function() {
    wx.login({
      success: res => {
        wx.request({
          url: 'http://47.94.6.186:3001/api/user/wxlogin',
          method: 'POST',
          data: { code: res.code },
          success: r => {
            if (r.data.code === 200) {
              wx.setStorageSync('token', r.data.data.token);
              wx.setStorageSync('userid', r.data.data.userid);
              wx.showToast({
                title: '登录成功，正在刷新购物车',
                icon: 'success'
              });
              this.getCartList();
            } else {
              wx.showToast({
            title: '登录失败，请重试',
            icon: 'none'
          });
        }
          },
          fail: err => {
            wx.showToast({
              title: '网络异常，登录失败',
              icon: 'none'
            });
          }
        });
      },
      fail: err => {
        wx.showToast({
          title: '获取登录信息失败',
          icon: 'none'
        });
      }
    });
  }
});